# SaveManager.gd
extends Node

const SAVE_FILE_PATH = "user://savegame.cfg"

# Data structure for saved game
var save_data = {
	"meta_currency": 0,
	"unlocked_levels": 1, # Start with level 1 unlocked
	"permanent_upgrades": {
		# "stat_name": level
		"base_health_bonus": 0,
		"global_damage_bonus": 0,
		# Add more permanent upgrades here
	},
	"achievements": {
		# "achievement_id": unlocked (bool)
	}
}

func _ready():
	load_game()
	print("SaveManager Ready")


func save_game():
	var config = ConfigFile.new()
	config.set_value("PlayerData", "meta_currency", save_data["meta_currency"])
	config.set_value("PlayerData", "unlocked_levels", save_data["unlocked_levels"])

	# Save permanent upgrades
	for key in save_data["permanent_upgrades"]:
		config.set_value("PermanentUpgrades", key, save_data["permanent_upgrades"][key])

	# Save achievements
	for key in save_data["achievements"]:
		config.set_value("Achievements", key, save_data["achievements"][key])

	var error = config.save(SAVE_FILE_PATH)
	if error != OK:
		printerr("Error saving game: ", error)
	else:
		print("Game saved successfully.")


func load_game():
	var config = ConfigFile.new()
	var error = config.load(SAVE_FILE_PATH)

	if error != OK:
		if error == ERR_FILE_NOT_FOUND:
			print("No save file found. Using default values.")
			# Optionally save default values immediately
			# save_game()
		else:
			printerr("Error loading game: ", error)
		return

	# Load player data
	save_data["meta_currency"] = config.get_value("PlayerData", "meta_currency", 0)
	save_data["unlocked_levels"] = config.get_value("PlayerData", "unlocked_levels", 1)

	# Load permanent upgrades (ensure keys exist in default save_data)
	for key in save_data["permanent_upgrades"]:
		save_data["permanent_upgrades"][key] = config.get_value("PermanentUpgrades", key, 0)

	# Load achievements (ensure keys exist in default save_data)
	for key in save_data["achievements"]:
		save_data["achievements"][key] = config.get_value("Achievements", key, false)

	print("Game loaded successfully.")


# --- Getters/Setters for safe access ---

func get_meta_currency() -> int:
	return save_data["meta_currency"]

func add_meta_currency(amount: int):
	save_data["meta_currency"] += amount
	# Optionally save immediately or rely on explicit save calls

func get_unlocked_levels() -> int:
	return save_data["unlocked_levels"]

func unlock_level(level_index: int):
	save_data["unlocked_levels"] = max(save_data["unlocked_levels"], level_index + 1) # level_index is 0-based

func get_permanent_upgrade_level(stat_name: String) -> int:
	return save_data["permanent_upgrades"].get(stat_name, 0)

func purchase_permanent_upgrade(stat_name: String, cost: int) -> bool:
	if save_data["permanent_upgrades"].has(stat_name) and save_data["meta_currency"] >= cost:
		save_data["meta_currency"] -= cost
		save_data["permanent_upgrades"][stat_name] += 1
		save_game() # Save after purchase
		return true
	return false

func is_achievement_unlocked(achievement_id: String) -> bool:
	return save_data["achievements"].get(achievement_id, false)

func unlock_achievement(achievement_id: String):
	if save_data["achievements"].has(achievement_id):
		save_data["achievements"][achievement_id] = true
		# Optionally save immediately